/* $Id:cache.h jjs $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#ifndef __CACHE_H
#define __CACHE_H

#include <string>
#include <glibmm.h>
#include <gdkmm.h>
#include "../general/hashtable.h"

class picture {
  public:
    picture(std::string k);
    std::string key; ///< Key of this image
    Glib::RefPtr<Gdk::Pixbuf> image; ///< Image payload
    picture *higher; ///< The next more recently used image or NULL
    picture *lower; ///< The next later used image or NULL
};

/** Cache images in memory to prevent constant reloading of image files
  This cache automatically loads files when needed and returns images.
  It has a cleanup routine that performs cleanup in steps of maximal 10 images
  so the cleanup won't take too much resources.
*/
class cache {
  private:
    picture *lowest; ///< Last used image or NULL when cache is empty
    picture *highest; ///< Most recently used image or NULL when cache is empty
    int elements; ///< Total number of images in cache
    hashtable<const char,picture> data; ///< Hash table for quick retrieval of cached images
  public:
    cache();
    picture &operator[](std::string key); ///< Get a (new) picture
    bool exists(std::string key); ///< Check if a picture exists in cache
    void clean(int max); ///< Remove elements from cache when full
    void dump(); ///< Write and check all elements inside the cache
};

#endif // __CACHE_H
